package com.itlong.cloud.operate.service.impl;

import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.PO.WwLyOperateAppProjectPO;
import com.itlong.cloud.POJO.VO.operate.WwLyOperateAppInfoVO;
import com.itlong.cloud.POJO.VO.operate.WwLyOperateProjectInfoVO;
import com.itlong.cloud.POJO.VO.operate.WwOperateDeveloperAccountVO;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.operate.dao.IOperateWwAppDao;
import com.itlong.cloud.operate.service.IOperateWwAppService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.Md5;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.string.StringUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.mail.FetchProfile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <des>
 *    开发者应用业务处理接口实现类
 * <des>
 *
 * @create Date 2021-08-18
 **/
@Service
@RefreshScope
public class IOperateWwAppServiceImpl implements IOperateWwAppService {

    @Autowired
    IOperateWwAppDao iOperateWwAppDao;
    //FTP服务器连接参数

    public static String FILE_FTP_HOST="localhost";

    public static String FILE_FTP_PORT="21";

    public static String FILE_FTP_USERNAME="itlongftp";

    public static String FILE_FTP_PASSWORD="Itlongserver%2017";

    public static String FILE_ACCESS_URL="http://localhost:8080/";


    /**
    * <desc>
    *      获取应用列表
    * </desc>
    * @param wwOperateSelectAppDTO
    * @return: com.itlong.cloud.utils.page.Page<com.itlong.cloud.POJO.VO.operate.WwOperateAppInfoVO>
    * @author LiuYu
    * @date: 2021-08-18
     **/
    @Override
    public Page<WwLyOperateAppInfoVO> getAppPageList(WwOperateSelectAppDTO wwOperateSelectAppDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwOperateSelectAppDTO);
        Page<WwLyOperateAppInfoVO> page= new Page<>();
        page.getPage().setCurrentPage(wwOperateSelectAppDTO.getCurrentPage());
        page.getPage().setPageSize(wwOperateSelectAppDTO.getPageSize());
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        List<WwLyOperateAppInfoVO> lyOperateAppInfoVOS = iOperateWwAppDao.getAppPageList(params);
        String appIds="";
        //获取应用id
        if(lyOperateAppInfoVOS != null){
            for (WwLyOperateAppInfoVO wwLyOperateAppInfoVO: lyOperateAppInfoVOS){
                appIds+=wwLyOperateAppInfoVO.getAppId()+",";
        }
        }
        //获取应用关联项目
        List<WwLyOperateProjectInfoVO> wwLyOperateProjectInfoVOS = iOperateWwAppDao.getProjectPageList(appIds);
        //设置关联项目列表
        if(wwLyOperateProjectInfoVOS != null) {
            for (WwLyOperateAppInfoVO wwLyOperateAppInfoVO: lyOperateAppInfoVOS){
                List<WwLyOperateProjectInfoVO> list = new ArrayList<>();
                for (WwLyOperateProjectInfoVO wwLyOperateProjectInfoVO : wwLyOperateProjectInfoVOS) {
                    if(wwLyOperateProjectInfoVO.getAppId().equals(wwLyOperateAppInfoVO.getAppId())){
                        list.add(wwLyOperateProjectInfoVO);
                    }
                }
                wwLyOperateAppInfoVO.setProjects(list);
            }
        }
        //设置有效期
        if(lyOperateAppInfoVOS != null) {
            for (WwLyOperateAppInfoVO wwLyOperateAppInfoVO : lyOperateAppInfoVOS) {
                if(wwLyOperateAppInfoVO.getProjects().size()>0){
                    for(WwLyOperateProjectInfoVO wwLyOperateProjectInfoVO:wwLyOperateAppInfoVO.getProjects()){
                        //设置有效期
                        String flag=new String();
                        //2表示未授权
                        if(wwLyOperateProjectInfoVO.getAuthValidityPeriodSettype() == 2){
                            flag="未授权";
                            wwLyOperateProjectInfoVO.setEffectTime(flag);
                        }
                        // 1表示长期有效
                        if(wwLyOperateProjectInfoVO.getAuthValidityPeriodSettype() == 1){
                            flag="长期有效";
                            wwLyOperateProjectInfoVO.setEffectTime(flag);
                        }
                        // 0表示自定义
                        if(wwLyOperateProjectInfoVO.getAuthValidityPeriodSettype() == 0){
                            //30天以上是正常
                            if(diffDays(new Date(),wwLyOperateProjectInfoVO.getEffectEndTime())>30){
                                flag="正常";
                            }
                            //30天以内是即将到期
                            else if(diffDays(new Date(),wwLyOperateProjectInfoVO.getEffectEndTime())>0){
                                flag="即将到期";
                            }
                            else{
                                flag="已经到期";
                            }
                            StringBuilder stringBuilder = new StringBuilder();
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            stringBuilder.append(dateFormat.format(wwLyOperateProjectInfoVO.getEffectStartTime())).append("-")
                                    .append(dateFormat.format(wwLyOperateProjectInfoVO.getEffectEndTime())).append("(")
                                    .append(flag).append(")");
                            wwLyOperateProjectInfoVO.setEffectTime(stringBuilder.toString());
                        }
                    }
                }
            }
        }
        //返回数据
        page.setRows(lyOperateAppInfoVOS,iOperateWwAppDao.getPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      计算日期相差天数
     * </desc>
     * @param effectStartTime
     * @param effectEndTime
     * @return: long
     * @author LiuYu
     * @date: 2021-08-23
     **/
    public static long diffDays(Date effectStartTime,Date effectEndTime){
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(effectStartTime);
        calendar2.setTime(effectEndTime);
        return (calendar2.getTimeInMillis()-calendar1.getTimeInMillis())/(24*60*60*1000);
    }


    /**
     * <desc>
     * 创建应用
     * </desc>
     *
     * @param wwLyOperateCreateAppInfoDTO
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-19
     **/
    @Override
    public Integer save(WwLyOperateCreateAppInfoDTO wwLyOperateCreateAppInfoDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwLyOperateCreateAppInfoDTO);
        params.put("appId",LogicIdUtil.bussinessId());
        params.put("appSecret",LogicIdUtil.bussinessId());
        params.put("status",DataStatusEnum.NORMAL.getType());
        Map<String,Object> params1 = new HashMap<>();
        //保存应用关联的项目信息
        List<WwLyOperateAppProjectPO> list = new ArrayList<>();
        String[] projectIds = StringUtils.isBlank(wwLyOperateCreateAppInfoDTO.getProjectId())==true?new String[]{}:wwLyOperateCreateAppInfoDTO.getProjectId().split(",");
        for(int i=0;i<projectIds.length;i++) {
            WwLyOperateAppProjectPO wwLyOperateAppProjectPO = new WwLyOperateAppProjectPO();
            wwLyOperateAppProjectPO.setAppProjectId(LogicIdUtil.bussinessId());
            wwLyOperateAppProjectPO.setAppId((String)params.get("appId"));
            wwLyOperateAppProjectPO.setProjectId(projectIds[i]);
            wwLyOperateAppProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
            wwLyOperateAppProjectPO.setAuthValidityPeriodSettype(DataStatusEnum.BAN.getType());//默认未授权
            wwLyOperateAppProjectPO.setCreateUserId(wwLyOperateCreateAppInfoDTO.getLoginUserId());
            list.add(wwLyOperateAppProjectPO);
        }
        if(list.size()>0) {
            iOperateWwAppDao.saveAppProject(list);
        }
        return iOperateWwAppDao.save(params);
    }
    /**
     * <desc>
     * 修改应用
     * </desc>
     *
     * @param wwLyOperateUpdateAppInfoDTO
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-19
     **/
    @Override
    public Integer update(WwLyOperateUpdateAppInfoDTO wwLyOperateUpdateAppInfoDTO) throws Exception {
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(wwLyOperateUpdateAppInfoDTO);
        String appId = wwLyOperateUpdateAppInfoDTO.getAppId();
        //修改的项目id
        List<String> nowProjectIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(wwLyOperateUpdateAppInfoDTO.getProjectId())) {
            nowProjectIdList = Arrays.asList(wwLyOperateUpdateAppInfoDTO.getProjectId().split(","));
        }
        List<WwLyOperateAppProjectPO> originAppProjects = iOperateWwAppDao.getAppProjects(appId);
        // 查询相同的项目id集合
        List<String> commonProjectIds = new ArrayList<>();
        for (String projectId : nowProjectIdList) {
            commonProjectIds = originAppProjects.stream().filter(a -> projectId.equals(a.getProjectId()))
                    .map(WwLyOperateAppProjectPO :: getProjectId).collect(Collectors.toList());
        }
        // 新增项目集合
        List<String> addProjectIds = new ArrayList<>();
        for (String projectId : nowProjectIdList) {
            if (!commonProjectIds.contains(projectId)) {
                addProjectIds.add(projectId);
            }
        }
        if (CollectionUtils.isNotEmpty(addProjectIds)) {
            List<WwLyOperateAppProjectPO> appProjectPOS = new ArrayList<>();
            for (String s: addProjectIds){
                WwLyOperateAppProjectPO wwLyOperateAppProjectPO = new WwLyOperateAppProjectPO(LogicIdUtil.bussinessId(),wwLyOperateUpdateAppInfoDTO.getAppId(),s,DataStatusEnum.BAN.getType(),wwLyOperateUpdateAppInfoDTO.getLoginUserId()
                ,DataStatusEnum.NORMAL.getType());
                appProjectPOS.add(wwLyOperateAppProjectPO);
            }
            iOperateWwAppDao.saveAppProject(appProjectPOS);
        }
        // 删除项目集合
        List<String> deletedAppIdList = new ArrayList<>();
        for (WwLyOperateAppProjectPO delete : originAppProjects) {
            if (!commonProjectIds.contains(delete.getProjectId())) {
                deletedAppIdList.add(delete.getAppProjectId());
            }
        }
        String deleteAppIds = StringUtils.join(deletedAppIdList, ",");
        if (StringUtils.isNotBlank(deleteAppIds)) {
            iOperateWwAppDao.deleteAppProjects(deleteAppIds);
        }
        return iOperateWwAppDao.update(params);
    }

    /**
     * <desc>
     * 查询开发者账号列表
     * </desc>
     *
     * @param wwOperateSelectDeveloperAccountDTO
     * @return: com.itlong.cloud.utils.page.Page<com.itlong.cloud.POJO.VO.operate.WwOperateDeveloperAccountVO>
     * @author LiuYu
     * @date: 2021-08-19
     **/
    @Override
    public Page<WwOperateDeveloperAccountVO> getDeveloperAccountPageList(WwOperateSelectDeveloperAccountDTO wwOperateSelectDeveloperAccountDTO) throws Exception {
//        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwOperateSelectDeveloperAccountDTO);
//        Page<WwOperateDeveloperAccountVO> page= new Page<>();
//        page.getPage().setCurrentPage(wwOperateSelectDeveloperAccountDTO.getCurrentPage());
//        page.getPage().setPageSize(wwOperateSelectDeveloperAccountDTO.getPageSize());
//        params.put("currentPage",page.getPage().getStartSlip());
//        params.put("pageSize",page.getPage().getPageSize());
//        page.setRows(iOperateWwAppDao.getDeveloperAccountPageList(params),iOperateWwAppDao.getDeveloperAccountPageCount(params));
//        return page;
        return null;
    }

//    /**
//     * <desc>
//     * 查询项目列表
//     * </desc>
//     *
//     * @param wwOperateSelectProjectDTO
//     * @return: com.itlong.cloud.utils.page.Page<com.itlong.cloud.POJO.VO.operate.WwOperateProjectInfoVO>
//     * @author LiuYu
//     * @date: 2021-08-19
//     **/
//    @Override
//    public Page<WwOperateProjectInfoVO> getProjectPageList(WwOperateSelectProjectDTO wwOperateSelectProjectDTO) throws Exception {
//        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwOperateSelectProjectDTO);
//        Page<WwOperateProjectInfoVO> page= new Page<>();
//        page.getPage().setCurrentPage(wwOperateSelectProjectDTO.getCurrentPage());
//        page.getPage().setPageSize(wwOperateSelectProjectDTO.getPageSize());
//        params.put("currentPage",page.getPage().getStartSlip());
//        params.put("pageSize",page.getPage().getPageSize());
//        page.setRows(iOperateWwAppDao.getProjectPageList(params),iOperateWwAppDao.getProjectPageCount(params));
//        return page;
//    }

    /**
     * <desc>
     * 添加开发者账号
     * </desc>
     *
     * @param wwLyCreateDeveloperAccountDTO
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-19
     **/
    @Override
    public Integer saveDeveloperAccount(WwLyCreateDeveloperAccountDTO wwLyCreateDeveloperAccountDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwLyCreateDeveloperAccountDTO);
        String developerAccount =   (String)params.get("developerAccount");
        //检验账号是否重复
        if(iOperateWwAppDao.getDeveloperAccountPageCount(developerAccount)>0){
            throw new DataAccessException("【】账号重复");
        }
        String imgUrl="";
        if(!StringUtils.isBlank(wwLyCreateDeveloperAccountDTO.getImgBase64())){
            imgUrl = uploadImage(wwLyCreateDeveloperAccountDTO.getImgBase64());
        }
        params.put("status",DataStatusEnum.NORMAL.getType());
        params.put("password",Md5.En(wwLyCreateDeveloperAccountDTO.getPassword()));
        params.put("developerAccountId",LogicIdUtil.bussinessId());
        params.put("imgUrl",imgUrl);
        return iOperateWwAppDao.saveDeveloperAccount(params);
    }

    /**
     * <desc>
     * 安全设置
     * </desc>
     *
     * @param ipAddresses
     * @param appId
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-23
     **/
    @Override
    public Integer updateSecuritySetting(String ipAddresses, String appId) {
        return iOperateWwAppDao.updateSecuritySetting(ipAddresses,appId);
    }

    /**
     * <desc>
     * 启用禁用
     * </desc>
     *
     * @param status
     * @param appId
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-23
     **/
    @Override
    public Integer updateStatus(Integer status, String appId) {
        return iOperateWwAppDao.updateStatus(status,appId);
    }

    /**
     * <desc>
     * 有效期授权
     * </desc>
     *
     * @param wwLyOperateUpdateEffectTimeDTO
     * @return: java.lang.Integer
     * @author LiuYu
     * @date: 2021-08-23
     **/
    @Override
    public Integer updateEffectTime(WwLyOperateUpdateEffectTimeDTO wwLyOperateUpdateEffectTimeDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(wwLyOperateUpdateEffectTimeDTO);
        return iOperateWwAppDao.updateEffectTime(params);
    }

    /**
     * <desc>
     * 上传图片
     * </desc>
     *
     * @param imgBase64
     * @return: java.lang.String
     * @author LiuYu
     * @date: 2021-08-19
     **/
    public static String uploadImage(String imgBase64) throws IOException {
        String imgUrl ="";
        //根目录
        String FileCatalogName = FileCatalogEnum.ADVERTISING_FILE.getType();
        try{
            // 图像数据为空
            if (StringUtils.isBlank(imgBase64)){
                return imgUrl;
            }
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgBase64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            InputStream inputStream = new ByteArrayInputStream(b);
            UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                    FILE_FTP_HOST,
                    FILE_FTP_USERNAME,
                    FILE_FTP_PASSWORD,
                    FILE_FTP_PORT,
                    inputStream,
                    "jpg",
                    FILE_ACCESS_URL,
                    FileCatalogName
            );
            long startTime = System.currentTimeMillis(); //程序开始记录时间
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            long endTime   = System.currentTimeMillis(); //程序结束记录时间
            long TotalTime = endTime - startTime;       //总消耗时间
            System.out.print(String.format("上传一张图片耗时：%s 毫秒\t\n",TotalTime));
            if ("true".equals(resultMap.get("returnCode").toString())){
                imgUrl = resultMap.get("accessPath").toString();
            }
        }catch (Exception e){
            throw new DataAccessException("【上传图片uploadImage】上传图片资源失败",e);
        }
        return imgUrl;
    }
}




